<template>
	<view class="infoLayout">
		<view class="avatar">
			<view class="box">
				<view class="avatar-box" @click="">
					<image :src="userInfo.avatar || '/static/defAvatar.png'" mode="scaleToFill"></image>
					<button open-type="chooseAvatar" @click="uploadAvatarImg" @chooseavatar="onChooseAvatar"
						class="btn">按钮</button>
				</view>
				<view class="icon">
					<uni-icons type="camera" color="#fff" size="16"></uni-icons>
				</view>
			</view>
			<view class="text">点击更换头像</view>
		</view>

		<uni-list class="uni-list-section">
			<uni-list-item class="item" @click="nicknameClick" title="昵称" :rightText="userInfo.nickname||'未设置'" link>
			</uni-list-item>

			<uni-list-item class="item" @click="genderClick" title="性别" :rightText="genderFromValue(userInfo.gender)"
				link>
			</uni-list-item>
			<uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'" link>
			</uni-list-item>
			<!-- #ifdef APP -->
			<!-- 如未开通实人认证服务，可以将实名认证入口注释 -->
			<uni-list-item class="item" @click="realNameVerify" title="实名认证"
				:rightText="realNameStatus !== 2 ? '未认证': '已认证'" link>
			</uni-list-item>
			<!-- #endif -->

			<uni-list-item class="item" @click="bindEnterprise" title="所属企业"
				:rightText="enterprise_info?.name ||'未绑定，点击绑定企业'" link>
			</uni-list-item>

			<uni-list-item class="item" @click="changePassword" title="修改密码" link>
			</uni-list-item>
			<uni-list-item class="item" @click="logout" title="退出登录" link>
			</uni-list-item>
		</uni-list>

	</view>

	<uni-popup ref="nickname_popup">
		<uni-popup-dialog mode="input" title="修改昵称" placeholder="请输入昵称(20字符以内)" @confirm="nickname_popup_confirm"
			v-model="nickname" :value='nickname' inputType="nickname"></uni-popup-dialog>
	</uni-popup>

	<uni-popup ref="gender_popup">
		<uni-popup-dialog title="修改性别" @confirm="gender_popup_confirm" mode="input">
			<radio-group @change="radio_change">
				<label class="radio-label" v-for="key in Object.keys(genderMap)" :key="key">
					<radio :value="key" :checked="gender == key" /><text></text>
					{{genderMap[key]}}
				</label>
			</radio-group>
		</uni-popup-dialog>
	</uni-popup>

	<!-- 	<uni-popup ref="enterprise_popup">
		<view class="picker_container flex-row">
			<scroll-view scroll-y>
				<view v-for="(item,index) in enterprises" :key="item._id" class="picker_item flex-row"
					@click="onPickerChange(item)">
					<view class="picker_logo">
						<image :src="item.logo[0]?.url" mode="heightFix"></image>
					</view>
					<view class="picker_info flex-1">
						<view class="name">{{item.name}}</view>
						<view class="corporate_legal_person">法人：{{item.corporate_legal_person}}</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</uni-popup> -->

	<uni-popup ref="enterprise_popup">
		<uni-popup-sheet>
			<view v-for="(item,index) in enterprises" :key="item._id" class="picker_item flex-row"
				@click="onPickerChange(item)">
				<view class="picker_logo">
					<image :src="item.logo[0]?.url" mode="heightFix"></image>
				</view>
				<view class="picker_info flex-1">
					<view class="name">{{item.name}}</view>
					<view class="corporate_legal_person">法人：{{item.corporate_legal_person}}</view>
				</view>
			</view>
		</uni-popup-sheet>
	</uni-popup>

</template>

<script setup>
	import {
		genderMap,
		genderFromValue
	} from '@/utils/userinfo.js'

	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'

	import {
		computed,
		ref
	} from 'vue'

	import {
		pt_upload
	} from '@/utils/uploadFile.js'


	import {
		onLoad
	} from '@dcloudio/uni-app'

	const userInfo = computed(() => store.userInfo)

	const nickname = ref(userInfo.nickname)
	const nickname_popup = ref(null)

	const gender = ref(userInfo.gender || '0')
	const gender_popup = ref(null)

	const enterprise = uniCloud.importObject('opendb-enterprise')
	const enterprise_info = ref(null)
	const enterprises = ref([])
	const enterprise_popup = ref(null)

	const isPC = ref(!['ios', 'android'].includes(uni.getSystemInfoSync().platform))

	onLoad(async () => {
		if (!userInfo.value.enterprise_id) {
			return
		}
		let res = await enterprise.opendb_enterprise_detail(userInfo.value.enterprise_id[0])
		if (res.errCode == 0) {
			enterprise_info.value = res.data
		}
	})

	function realNameVerify() {
		uni.navigateTo({
			url: "/uni_modules/uni-id-pages/pages/userinfo/realname-verify/realname-verify"
		})
	}

	function onChooseAvatar(params) {
		let tempFiles = [{
			path: params.detail.avatarUrl
		}]
		uploading(tempFiles)
	}

	async function uploadAvatarImg() {
		// #ifdef MP-WEIXIN
		return
		// #endif
		// #ifndef MP-WEIXIN
		const crop = {
			quality: 100,
			width: 600,
			height: 600,
			resize: true
		};
		let res = await uni.chooseImage({
			count: 1,
			crop
		})
		//非app端剪裁头像，app端用内置的原生裁剪
		// #ifdef H5
		if (!isPC.value) {
			let tempFile = res.tempFilePaths[0]
			// 非app端剪裁头像，app端用内置的原生裁剪，裁剪之后是一个base64字符串
			tempFile = await new Promise((callback) => {
				uni.navigateTo({
					url: '/uni_modules/uni-id-pages/pages/userinfo/cropImage/cropImage?path=' +
						tempFile + `&options=${JSON.stringify(crop)}`,
					animationType: "fade-in",
					events: {
						success: url => {
							callback(url)
						}
					},
					complete(e) {
						console.log(e);
					}
				});
			})
			res.tempFiles = [{
				path: tempFile
			}]
		}
		// #endif
		uploading(res.tempFiles)
		// #endif
	}

	async function uploading(tempFiles) {
		// 上传头像
		uni.showLoading({
			title: "更新中",
			mask: true
		});
		let [{
			fileID: avatar
		}] = await pt_upload(tempFiles)
		let avatar_file = {
			extname: avatar.substring(avatar.lastIndexOf('.') + 1),
			name: avatar.substring(avatar.lastIndexOf('/') + 1, avatar.lastIndexOf('.')),
			url: avatar
		}
		console.log('avatar_file', avatar_file);
		mutations.updateUserInfo({
			avatar,
			avatar_file
		})
		uni.hideLoading()
	}

	function nicknameClick() {
		nickname.value = userInfo.value.nickname
		nickname_popup.value.open()
	}

	function genderClick() {
		gender.value = userInfo.value.gender || 0
		gender_popup.value.open()
	}

	// 绑定手机号
	function bindMobile(params) {
		// #ifdef APP-PLUS
		uni.preLogin({
			provider: 'univerify',
			success: preLoginSuccess,
			fail: (fail) => {
				bindMobileBySmsCode()
			}
		})
		// #endif
		// #ifndef APP-PLUS
		bindMobileBySmsCode()
		// #endif
	}

	function onPickerChange(e) {
		enterprise_popup.value.close()
		let enterprise_id = userInfo.value.enterprise_id || []
		if (enterprise_id.includes(e._id)) {
			return
		}
		enterprise_info.value = e
		enterprise_id = [e._id]
		mutations.updateUserInfo({
			enterprise_id
		})
	}

	/* 绑定企业 */
	async function bindEnterprise() {
		let res = await enterprise.opendb_enterprise_all()
		if (res.errCode == 0) {
			enterprises.value = res.data
		}
		enterprise_popup.value.open('bottom')
	}

	// 预登陆成功
	function preLoginSuccess(params) {
		console.log('preLoginSuccess', preLoginSuccess);
	}

	function bindMobileBySmsCode() {
		uni.navigateTo({
			url: '/uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile'
		})
	}

	function changePassword() {
		uni.navigateTo({
			url: '/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd',
		})
	}

	function logout() {
		mutations.logout()
	}

	function nickname_popup_confirm(params) {
		if (params.length == 0) {
			uni.showToast({
				title: '昵称不能为空'
			})
			return
		}
		if (params.length > 20) {
			uni.showToast({
				title: '昵称长度不能超过20个字符'
			})
			return
		}
		mutations.updateUserInfo({
			nickname: params
		})
	}

	function radio_change(params) {
		gender.value = Number(params.detail.value)
	}

	function gender_popup_confirm(params) {
		mutations.updateUserInfo({
			gender: gender.value
		})
	}

	function getuserinfo(params) {
		console.log(params);
	}
</script>

<style lang="scss" scoped>
	.infoLayout {
		.avatar {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin: 50rpx 0rpx 0rpx;

			.box {
				position: relative;

				.avatar-box {
					width: 150rpx;
					height: 150rpx;
					border-radius: 50%;
					overflow: hidden;

					.btn {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						border-radius: 50%;
						opacity: 0;
					}

					image {
						width: 100%;
						height: 100%;
					}
				}

				.icon {
					width: 50rpx;
					height: 50rpx;
					background: #FE9468;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 2px solid #fff;
					position: absolute;
					right: 0;
					bottom: 0;
					pointer-events: none;
				}
			}

			.text {
				font-size: 25rpx;
				color: #999;
				white-space: nowrap;
				padding: 20rpx 0;
				text-align: center;
			}
		}

		.uni-list-section {
			margin-top: 50rpx;

			.uni_list_getUserInfo_box {
				position: relative;

				.getUserInfo {
					position: absolute;
				}
			}

			.item {
				flex: 1;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
			}
		}
	}

	.picker_item {
		padding: 28rpx 0;
		border-bottom: 1rpx solid $me-color-background;

		.picker_logo {
			width: 200rpx;
			display: flex;
			justify-content: flex-end;
			align-items: flex-end;

			image {
				height: 100%;
			}
		}

		.picker_info {
			margin-left: 20rpx;
			align-items: center;

			.name {
				font-size: 28rpx;
				color: $me-color-gray-1;
			}

			.corporate_legal_person {
				font-size: 24rpx;
				color: $me-color-gray-7;
			}
		}

	}

	.radio-label {
		padding: 0 10rpx;
	}
</style>